Python OOP datatype [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Why does it say 'Die eingegebenen Daten haben den falschen Datentyp!' when the datatypes are actually right? Doesn't even work with just matrNr... Although I checked my input of matrNr to be an int?!
class Student:
def __init__(self):
self.matrNr = -1
self.vorname = ''
self.nachname = ''
self.gebDatum = []
self.email = ''
self.telNr = ''
def DatenUebergeben(self, matrNr, vorname, nachname, gebDatum, telNr):
if matrNr == int and vorname == str and nachname == str and gebDatum == list and telNr == str:
print('richtige Datentypen!')
else:
print('Die eingegebenen Daten haben den falschen Datentyp!')
student1 = Student()
student1.DatenUebergeben(12345,'linda','f',[2,2,1995],'12345')

Background
By checking (for example) matrNr == int you actually compare the variable matNr, which is an int (an instance of <class 'int'>) to the class int (<class 'int'>).
Quick fix
You can use the type()-function to get the type of a variable, resulting in type(matrNr) == int. This does exactly what you are trying to achieve.
Better solution
In Python you can define the types of variables a function accepts by adding : <type> after the argument. The better solution would thus be:
def DatenUebergeben(self, matrNr: int, vorname: str, nachname: str, gebDatum: list, telNr: str):
# do something

Related

How to build Observable/Observer pattern in Python without classes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I want to create something like "Svelte Stores" in python. Svelte stores implements the Observable (store)/Observer (subscriber) pattern in a highly composable way: a functional style, which I am trying to mimic.
In the original code, you have:
export type Subscriber<T> = (value: T) => void;
export type Unsubscriber = () => void;
export type Updater<T> = (value: T) => T;
export interface Readable<T> {
subscribe(...): Unsubscriber;
}
export interface Writable<T> extends Readable<T> {
update(this: void, updater: Updater<T>): void;
}
I tried:
from typing import Callable, TypeVar, Generic
T = TypeVar("T")
Subscriber = Callable[[T], None]
Unsubscriber = Callable[[], None]
class Store(Generic[T]):
def subscribe(self, subscriber: Subscriber[T]) -> Unsubscriber: ...
def update(self, fn: Updater[T]) -> None: ...
Store is an Observable that Subscribers(Observers) can listen. Everytime the value of the Store changes
def writable(value: T) -> Store[T]:
""" Create a writable store."""
subscriber_queue: list[Subscriber] = []
def subscribe(subscriber: Subscriber[T]) -> Unsubscriber:
subscriber_queue.append(subscriber)
subscriber(value)
def unsubscribe() -> None:
subscriber_queue.remove(subscriber)
return unsubscribe
def update(self, fn: TUpdater) -> None: fn(value)
ret = Store()
ret.subscribe = subscribe
ret.update = update
return ret
In the original implementation, writable is a factory function that creates an object (a POJO) with the subscribe and update functions. A Store (Writable in the original) is anything that has subscribe and update.
But dicts in python are different to POJOs in js.
In Python, I can't do something like:
user = writable({"name": "John", "age": 42})
name = user['name']
...,because I have no access to __getitem__ from dict.
I want to be able to access the store the same way I access an object of the type used to create the store. If I create a store with a dict which is subscriptable, I want the store to be subscriptable. If the store value is iterable, I want to be able to iterate on the store.
P.S. Edited to clarify my goal

Better way to use variables in this function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've got a function get_prefix_lists with returns two values, each is a list of strings.
I then want to use those lists separately in another function. My code below is how i've done it but it feels dirty to use the same variable name (prefixes) in the __main__ section.
Is there a less dirty way?
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
v4_prefixes = []
v6_prefixes = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
v4_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
v4_prefixes.append(result.prefix)
else:
v6_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
v6_prefixes.append(result.prefix)
return v4_prefixes, v6_prefixes
def get_radb_prefixes(prefixes):
for prefix in prefixes:
r = requests.get(url=radb_url + 'route/' + prefix + 'AS11111?password=' + radb_mnt_password, headers=headers)
if r.status_code == 200:
pass
elif r.status_code == 404:
print(f"{prefix} Is in NetBox but not RADB")
else:
print(r.status_code, r.text)
if __name__ == "__main__":
print("V4 check")
prefixes = get_radb_prefixes(get_prefix_lists()[0])
print("V6 check")
prefixes = get_radb_prefixes(get_prefix_lists()[1])
Why not returning a dictionary?
{"v4": [], "v6": []}
Here's just some quickly jotted code to better explain:
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
prefixes = {}
prefixes['v4'] = []
prefixes['v6'] = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
prefixes['v4'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
prefixes['v4'].append(result.prefix)
else:
prefixes['v6'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
prefixes['v6'].append(result.prefix)
return prefixes

can two different methods have different args in a class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to add the age for users in a different method but some users might not have an age argument
class User:
"""a class to save info about every user """
def __init__(self, user_name, num_id):
self.name = name
self.mun_id = num_id
def age(self, age):
self.age = age
user1 = User("martin", "1")
print (user1.name)
Yes you can set user age separately. Example below:
user1.age(20)
print (user1.age)
#20 will print
define age = None like below and this optional argument should be the last one:
def age(self, age = None):

Python Classes and Inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm studying Python programming and I'm having difficulty understanding Inheritance. My assignment is to:
Create a Division and Department class.
Create a method named “getList()” which will display a message, “The
dept department has fullTime full-time and partTime part-time
instructors.”
In the “Department” class, assign 12 as value to the fullTime
variable, assign 27 to partTime, and “CIS” to dept. DO NOT create
any method in the “Department” class. and
Create an instance (object) of the “Department” class named
“myDept”. Use this “myDept” object to call the “getList()” method of
“Division” class (through Inheritance).
Here's what I have so far.
class Division():
def __init__(self, dept, fullTime, partTime):
self.dept = dept
self.fullTime = fullTime
self.partTime = partTime
def getList(self):
return "The (0) department has (1) full-time and (2) part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
myDept = Division(CIS247, 12, 27)
class Division(object):
def __init__(self,dept, fullTime, partTime):
self.fullTime = fullTime
self.partTime = partTime
self.dept=dept
def getList(self):
return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
pass
myDept = Department("CIS",12,37)
print myDept.getList()
Edited, I missed the "CIS", for string formatting you use {} not ().
Also " DO NOT create any method in the “Department” class." so removed init method.
python classes tutorial

How to call/run a method only one time in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to call/run a method only onetime I tried this but it didn't wotk:
class S ()
_int_(self)
self.xxx = True # i tried with and without
def Packet (event):
if (xxx == True):
self.f(event, xxx)
print xxx
else:
....
def f (event):
print "something"
Do_Somthing
xxx=False
the problem xxx is still true
Best regards
Amer
The whole class's syntax seems wrong to me. You can do something like this
class S:
def __init__(self): # Initializer function for instance members
self.flag = True
def myMethod(self): # Actual method to be called
if self.flag:
....
....
self.flag = False
Change xxx to self.xxx.
The xxx = False creates a new name binding instead of assigning to the field in your object.
Also, there are also some other syntax errors in your code. Is this the actual code you are running? The code you posted shouldn't run.
from itertools import count
class S ()
def __init__(self)
self.xxx = count()
def Packet(self, event):
if next(self.xxx) == 0:
self.f(event)
else:
....
def f(self, event):
print "something"
#Do_Something

Categories

Resources