how to access or use name in class ? Python - python-3.x

Python Masters.
I am so curious about class name space.
for example, there some class definition.
import Another_class
class Some_class:
def __init__(self, city):
self.city = city
if self.city == "newyork":
newyork_info = Another_class(some_param)
def state(self):
if self.city == "newyork":
newyork_wether = newyork_info.get_wether()
newyork_population = newyork_info.get_population()
so, i tend to use "newyork_info" in another functions.
NameError: name 'newyork_info' is not defined
but i could not use the name in init function.
how could i solve it? Is there are good way? :)

You must assign newyork_info to the class.
self.newyork_info = Another_class(some_param)

Related

How Can I Dynamically Create Python Class Instances Using a List?

I am trying to understand how to dynamically create instances of a python class.
The simple example below shows how to create a class instance
class Person:
def __init__(self, name):
self.name = name
emmy = Person("Emmy")
niels = Person("Niels")
print(emmy.name)
print(niels.name)
If I want to iterate through a list to create class instances, how can I dynamically execute a command the same as
emmy = Person("Emmy")
I have tried to dynamically do it with something like eval or exec method so that I can iterate through a list and be able to call the class instance name using item name from list.
class Person:
def __init__(self, name):
self.name = name
people = ["Emmy","Niels"]
for item in people:
eval('item = Person(item)')
print(emmy.name)
print(niels.name)
Thanks in advance for any suggestions.
I found a solution creating a string variable to use as a command for the exec function.
class Person:
def __init__(self, name):
self.name = name
people = ["Emmy","Niels"]
for item in people:
a = str(item) + ' = Person("' + str(item) + '")'
exec(a)
print(Emmy.name)
print(Niels.name)

Can I take 'outer' class Attributes and use them in 'inner' class?

Can I take 'outer' class Attributes and use them in 'inner' class ?
I want to make an outer class that contains the name and age of a man and the inner class contains the age of a man.... I tried this way but VSC told me that this is a syntax error
I tried to search for a way to inherit from 'father_city' class and I found this but I didn't understand it
class father_city:
def __init__(self, city):
self.city = city
self.name = 'mark'
def show_city(self):
print(f"hello {self.name} you live in {self.city}")
class father_age:
def __init__(self, age):
self.age = age
def show_age(self):
print(f'hello {father_city('Ny').name} your age is {self.age}')
ob = father_city('Ny')
print(ob.father_age(26).show_age())
your show_age method has a syntax error,when using ' inside a fstring you should use " to surround the string.
print(f"hello {father_city('Ny').name} your age is {self.age}")

How can i avoid repetitive calling of instance variables in Subclasses?

i was wondering if there is a way in Python to get rid of repetitive calling of instance variables , when creating subclasses.
for example:
class Name:
def __init__(self,first,last):
self.first = first
self.last = last
def __str__(self):
return f"Users first name is : {self.first}, Users last name is: {self.last}"
def __repr__(self):
return f"first:{self.first}, last:{self.last}"
class Cash(Name):
def __init__(self,first,last,cash):
super().__init__(first,last)
self.cash = cash
def full(self):
return f"{self.first},{self.last},{self.cash}"
c1 = Cash("Exa","Cool",200)
print(c1.full())
Is it possible to call all instance variables (self.first,self.last...) from "Name", without having to mention them in the constructor of "Cash"
something like:
class Cash(Name):
def __init__("all from Name" + new one ("cash" in this example)):
super().__init__("all from Name")
self.cash = cash
In your case, you can change the Cash class to look like this:
class Cash(Name):
def __init__(self,*inputs):
super(Cash,self).__init__(*inputs[:-1])
self.cash = inputs[-1]
def full(self):
return f"{self.first},{self.last},{self.cash}"
but for a more general solution that covers all situations take a look at this similar question.

Python understanding classes and functions

New to python and have been working on improving my skills overall, however, I struggle with understanding classes and functions.
Why can or can't I do the following code below
class Person():
name = 'Tom'
age = 31
has_job = False
Person.name = 'Tom'
Person.age = 31
Person.has_job = False
print(Person.name, Person.age, Person.has_job)
compared to this
class Person():
def __init__(self, name, age, has_job):
self.name = name
self.age = age
self.has_job = has_job
p1 = Person('Tom', 31, False)
Is this just bad practice or is it something else entirely?
I don't think that writing a class like your first example would be very usefull, because the attributes remain the same for each instance.
That means that every Person will be called by default 'Tom', will have the age: 41 and "has_job" will be set to false.
In the second example you've got a specific constructor that will initialise those variables and that's going to be more usefull. There's only one problem: you forgot to put ":" after def __init__(self, name, age, has_job) .
Also be aware of the indentation.
Your code should look like this:
class Person():
def __init__(self, name, age, has_job):
self.name = name
self.age = age
self.has_job = has_job
p1 = Person('Tom', 31, False)
print(p1.name);
Python is white space sensitive. Unless you want to change the default values in you class you do not need to redefine them.
class Person():
name = 'Tom'
age = 31
has_job = False
'''
change these will change the class values
Person.name = 'Tom'
Person.age = 31
Person.has_job = False
'''
print(Person.name, Person.age, Person.has_job)
In the first section of your code you are trying to define class attributes. These are attributes that do not change between instances of your class. On the other hand if you define variables in the def init(self) method these are parameters you must pass when creating the class and will be unique to each instance of the class you create. These are called instance attributes.
class Person():
# these are class attributes.
name = 'Tom'
age = 31
has_job = False
class Person2():
def __init__(self, name, age, has_job)
# these are instance attributes
self.name = name
self.age = age
self.has_job = has_job
In your first code snippet you did not indent the classes attributes appropriately when you created the class. Check my example above to see how that would be done.
So in your case since each person will be a new instance of your Person class, you do not want to have name, age and has_job as class attributes since those are unique to every person you create. If you had those variables as class attributes then each person you create using your Person() class will have the same name, age, and has_job values.
If you created a class with class attributes and then changed the class attributes of the class instance every time it would not be pythonic. Rather you should create instances of the class with instance attributes.
I HIGHLY recommend watching Corey Shafer OOP tutorials on youtube as they cover all this extensively: https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=40

Create os.DirEntry

Does anyone have a hack to create an os.DirEntry object other than listing the containing directory?
I want to use that for 2 purposes:
tests
API where container and contained are queried at the same time
Yes, os.DirEntry is a low-level class not intended to be instantiated. For tests and things, you can create a mock PseudoDirEntry class that mimics the things you want, for example (taken from another answer I wrote here):
class PseudoDirEntry:
def __init__(self, name, path, is_dir, stat):
self.name = name
self.path = path
self._is_dir = is_dir
self._stat = stat
def is_dir(self):
return self._is_dir
def stat(self):
return self._stat
Even easier:
class PseudoDirEntry:
def __init__(self, path):
import os, os.path
self.path = os.path.realpath(path)
self.name = os.path.basename(self.path)
self.is_dir = os.path.isdir(self.path)
self.stat = lambda: os.stat(self.path)
In Python 3.5 os.DirEntry is not yet exposed.
Details: https://bugs.python.org/issue27038
Python 3.6 exposes os.DirEntry type, but it cannot be instantiated.
On Python 3.5 a type() on a DirEntry object returns posix.DirEntry

Resources